var axios = require('axios')
const db = uniCloud.database();
const dbCmd = db.command;

async function getWeatherData(city) {
	// console.log("getWeatherData")
	let mDate = __formatDateTime(new Date())
	console.log("mDate " + mDate)
	let weatherDb = await getWeatherDb(mDate, city)
	console.log("weatherDb " + JSON.stringify(weatherDb))
	if (weatherDb)
		return weatherDb
	return getWeatherApi(mDate, city)
}

// 请求天气接口 && 保存天气数据到数据库------------
async function getWeatherApi(mDate, city) {
	let weather_api = "http://apis.juhe.cn/simpleWeather/query?key=63e112f49617054c7c4b0e1627a7723f"
	const options = {
		method: 'POST',
		url: weather_api,
		data: {
			city
		},
		headers: {
			'content-type': 'application/x-www-form-urlencoded'
		}
	};
	let dbResult = await axios(weather_api,options).then(html => {
		let {data}=html
		console.log("axios-html " ,data)
		let weatherObj = data.result.realtime
		// 第一步，先保存天气到数据库得到id
		return saveWeatherDb(city, weatherObj, mDate)
	}).then(saveRes => {
		// 第二步，通过id得到数据
		console.log("Save-db-result " + JSON.stringify(saveRes))
		let saveId = saveRes.id
		return db.collection("weather").doc(saveId).get()
	})
	console.log("axios-result " + JSON.stringify(dbResult))
	let weather = dbResult.data[0].weather
	return weather
}

// 保存天气数据到数据库------------
async function saveWeatherDb(city, weather, mDate) {
	let result = await db.collection("weather").add({
		city,
		date: mDate,
		weather: weather,
	})
	return result
}

// 获取数据库天气数据------------
async function getWeatherDb(mDate, city) {
	let weatherData = await db.collection("weather").where({
		date: mDate,
		city
	}).get()
	// console.log("weatherDb-data", JSON.stringify(weatherData))
	weatherData = weatherData.data
	if (weatherData && weatherData.length > 0) {
		return weatherData[0].weather
	}
}

function __formatLeadingZeroNumber(n, digitNum = 2) {
	n = n.toString()
	const needNum = Math.max(digitNum - n.length, 0)
	return new Array(needNum).fill(0).join('') + n
}

//输出格式为：2019-10-30
function __formatDateTime(date) {
	const year = date.getFullYear()
	const month = date.getMonth() + 1
	const day = date.getDate()
	const hour = date.getHours()
	const minute = date.getMinutes()
	const second = date.getSeconds()
	const ms = date.getMilliseconds()

	let ret = [year, month, day].map(value => __formatLeadingZeroNumber(value, 2)).join('-') + ''
	return ret
}


module.exports = {
	getWeatherData
}
